import { createStore } from 'vuex'
import axios from 'axios'

// 创建一个专门用于认证的axios实例，配置baseURL以确保通过代理
const authClient = axios.create({
  baseURL: '', // 使用空字符串，这样相对路径会通过vue代理配置
  timeout: 15000, // 设置超时时间
});

export default createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token') || null,
    isAuthenticated: !!localStorage.getItem('token'),
    role: localStorage.getItem('role') || null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
      if (user) {
        localStorage.setItem('user', JSON.stringify(user))
      } else {
        localStorage.removeItem('user')
      }
    },
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_AUTH(state, isAuthenticated) {
      state.isAuthenticated = isAuthenticated
    },
    SET_ROLE(state, role) {
      state.role = role
      if (role) {
        localStorage.setItem('role', role)
      } else {
        localStorage.removeItem('role')
      }
    },
    LOGOUT(state) {
      state.user = null
      state.token = null
      state.isAuthenticated = false
      state.role = null
      localStorage.removeItem('user')
      localStorage.removeItem('token')
      localStorage.removeItem('role')
    }
  },
  actions: {
    async login({ commit }, { username, password }) {
      try {
        console.log('Attempting login with:', { username, password });
        
        const response = await authClient.post('/api/auth/login', {
          username,
          password
        })
        
        console.log('Response status:', response.status);
        console.log('Response data:', response.data);
        
        const data = response.data
        
        if (response.status === 200) {
          // Login successful
          commit('SET_USER', data.user)
          commit('SET_TOKEN', data.token)
          commit('SET_AUTH', true)
          commit('SET_ROLE', data.user.userType)
          
          // Set default authorization header for future requests
          if (data.token) {
            // You might want to set this in a global HTTP client instead
            // For now, we'll just store it
          }
          
          return {
            success: true,
            user: data.user,
            token: data.token
          }
        } else {
          // Login failed
          return {
            success: false,
            message: data.message || 'Invalid credentials'
          }
        }
      } catch (error) {
        console.error('Login error:', error)
        return {
          success: false,
          message: error.response?.data?.message || 'Network error. Please try again.'
        }
      }
    },
    logout({ commit }) {
      commit('LOGOUT')
    }
  },
  modules: {
  }
})